﻿using DSBase;
using DSPara;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using TYBase;
using TYControl;
using TYLitedbBase;

namespace DSParaView
{
    public partial class ViewSort : WindowT
    {
        IUserRole userRole;
        private ViewModelSortParaAt09 vm = new ViewModelSortParaAt09();
        private LiteDB_BaseHelper<Entity_SortPara> liteDBHelper;
        int levelCount = 0;
        public ViewSort(IUserRole userRole,
            string dbName,
            int _levelCount,
            string sectionId)
        {
            InitializeComponent();
            liteDBHelper = new LiteDB_BaseHelper<Entity_SortPara>(dbName, true);
            this.userRole = userRole;
            levelCount = _levelCount;
            this.DataContext = vm;

            listSortCtrl.Add(ctrl_ocv1);
            listSortCtrl.Add(ctrl_ir1);
            this.sectionId = sectionId;
            InitVM();
            for (int i = 0; i < vm.ListSortPara.Count; i++)
            {
                if (i < listSortCtrl.Count)
                {
                    listSortCtrl[i].DataContext = vm.ListSortPara[i];
                }
            }
            this.Loaded += ViewSortParaAt09_Loaded;
        }

        private string sectionId = "";
        private List<CtrlSortItem> listSortCtrl = new List<CtrlSortItem>();

        private void ViewSortParaAt09_Loaded(object sender, RoutedEventArgs e)
        {
            if (liteDBHelper.Get(x => x.SectionId == sectionId, out Entity_SortPara sortPara) && sortPara != null)
            {
                Data2UI(sortPara);
            }

        }

        private void InitVM()
        {
            string[] titles = new string[] { "OCV", "IR" };

            for (int i = 0; i < titles.Length; i++)
            {
                CtrlSortItemModel sortPara = new CtrlSortItemModel();
                for (int j = 0; j < levelCount; j++)
                {
                    sortPara.ListLevelData.Add(new CtrlLevelItemModel { AtLevel = j + 1 });
                }
                sortPara.Title = titles[i];
                vm.ListSortPara.Add(sortPara);
            }

            for (int i = 0; i < levelCount; i++)
            {
                vm.ListAtLevel.Add($"{i + 1}");
                vm.SlotModel.ListSlots.Add(new OneSlotModel { FromSlot = i + 1, ToSlot = i + 1 });
                vm.LotLimitModel.ListLotLimit.Add(new LotLimitOneLevelModel { level = i + 1, LotId = "" });
            }
        }



        private void Data2UI(Entity_LotPara lotPara)
        {
            if (lotPara == null)
                return;

            for (int j = 0; j < levelCount; j++)
            {
                var data = lotPara.ListLotItem.FirstOrDefault(x => x.AtLevel == j + 1);
                if (data != null && vm.SlotModel != null && j < vm.SlotModel.ListSlots.Count)
                {
                    vm.LotLimitModel.ListLotLimit[j].LotId = data.LotId?.ToUpper();
                }
            }
        }

        private void UI2Data(out Entity_SortPara entity_SortPara)
        {
            entity_SortPara = new Entity_SortPara() { SectionId = sectionId, IsDefault = true, TypeName = vm.Name };

            for (int j = 0; j < levelCount; j++)
            {
                Entity_SortPara_Level levelPara = new Entity_SortPara_Level();
                levelPara.AtLevel = j + 1;
                for (int i = 0; i < vm.ListSortPara.Count; i++)
                {
                    levelPara.ListSortItem.Add(new Entity_SortItem
                    {
                        Min = vm.ListSortPara[i].ListLevelData[j].MinVal,
                        Max = vm.ListSortPara[i].ListLevelData[j].MaxVal,
                        IsUse = vm.ListSortPara[i].IsUse,
                    });
                }
                entity_SortPara.ListSortPara.Add(levelPara);
                if (vm.SlotModel.ListSlots[j].ToSlot <= 0 || vm.SlotModel.ListSlots[j].ToSlot > levelCount)
                {
                    vm.SlotModel.ListSlots[j].ToSlot = j + 1;
                }
            }
        }

        private void Data2UI(Entity_SortPara sortPara)
        {
            if (sortPara == null)
                return;

            vm.Name = sortPara.TypeName;
            for (int j = 0; j < levelCount; j++)
            {
                for (int i = 0; i < vm.ListSortPara.Count; i++)
                {
                    if (j < sortPara.ListSortPara.Count && i < sortPara.ListSortPara[j].ListSortItem.Count)
                    {
                        vm.ListSortPara[i].ListLevelData[j].MinVal = sortPara.ListSortPara[j].ListSortItem[i].Min;
                        vm.ListSortPara[i].ListLevelData[j].MaxVal = sortPara.ListSortPara[j].ListSortItem[i].Max;
                        if (j == 0)
                        {
                            vm.ListSortPara[i].IsUse = sortPara.ListSortPara[j].ListSortItem[i].IsUse;
                        }
                    }
                }
            }
        }

        private void BtnClick_Save(object sender, RoutedEventArgs e)
        {
            if (vm.Name.Null())
            {
                MessageBox.Show("请输入名称");
                return;
            }
            if (userRole != null &&
                !userRole.CheckUserLevel(EnumUserLevel.系统管理员 | EnumUserLevel.设备管理))
            {
                return;
            }
            liteDBHelper.Delete(x => x.SectionId == sectionId);
            UI2Data(out Entity_SortPara data1);
            liteDBHelper.Insert(data1);
            MessageBox.Show("保存成功!");
        }

        private void BtnClick_SaveLocal(object sender, RoutedEventArgs e)
        {
            if (vm.Name.Null())
            {
                MessageBox.Show("请输入名称");
                return;
            }
            System.Windows.Forms.SaveFileDialog saveDg = new System.Windows.Forms.SaveFileDialog();
            saveDg.Filter = "(*.srt)|*.srt";
            saveDg.FileName = vm.Name;
            saveDg.AddExtension = true;
            saveDg.RestoreDirectory = true;
            if (saveDg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //此处做你想做的事
                string filePath = saveDg.FileName;
                UI2Data(out Entity_SortPara data1);
                var data = new LocalSortPara
                {
                    SortPara = data1,
                };
                System.IO.File.WriteAllText(filePath, data.JsonAsString(), Encoding.UTF8);
            }
        }

        private void BtnClickReadLocal(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            openFileDialog1.Filter = "(*.srt)|*.srt";
            openFileDialog1.RestoreDirectory = true;
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string fileName = openFileDialog1.FileName;
                string data = System.IO.File.ReadAllText(openFileDialog1.FileName, Encoding.UTF8);
                var para = data.AsModel<LocalSortPara>();
                if (para == null)
                {
                    MessageBox.Show("加载的数据为空!");
                    return;
                }
                FileInfo fileInfo = new FileInfo(fileName);
                if (para.SortPara != null)
                    para.SortPara.TypeName = fileInfo.Name;
                Data2UI(para.SortPara);
                MessageBox.Show("已加载!");
            }
        }

        private async void Btn_Click_ReadXls(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new Microsoft.Win32.OpenFileDialog()
            {
                Filter = "xls documents (.xls)|*.xls|xlsx documents (.xlsx)|*.xlsx"
            };
            var result = openFileDialog.ShowDialog();
            if (result != true)
            {
                return;
            }
            List<List<string>> listData = null;
            var fileName = openFileDialog.FileName;
            var ret = await Run(() =>
            {
                try
                {
                    FileInfo fi = new FileInfo(fileName);
                    string tmpFile = $"{AppDomain.CurrentDomain.BaseDirectory}\\tmp_{DateTime.Now.Ticks.ToString()}{fi.Extension}";
                    File.Copy(fileName, tmpFile);
                    var readRet = ExcelHelper.GetData(tmpFile, out listData);
                    File.Delete(tmpFile);
                    return readRet;
                }
                catch (Exception ex)
                {
                    Log.E("读取excel异常", ex);
                    return false;
                }
            });
            if (ret == false)
            {
                MessageBox.Show("文件导入失败!");
            }

            for (int j = 1; j < listData.Count; j++)
            {
                for (int i = 0; i + 1 < listData[j].Count; i += 2)
                {
                    if (i / 2 < vm.ListSortPara.Count && j - 1 < vm.ListSortPara[i / 2].ListLevelData.Count)
                    {
                        vm.ListSortPara[i / 2].ListLevelData[j - 1].MinVal = listData[j][i].AsDouble();
                        vm.ListSortPara[i / 2].ListLevelData[j - 1].MaxVal = listData[j][i + 1].AsDouble();
                    }
                }
            }
        }
    }
}